package com.eet.juc.fork;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * 测试Demo
 *
 * @author zheng.zhang
 */
public class TestDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        test1();
        test2();
        test3();
    }

    /**
     * 普通求和计算
     */
    public static void test1() {
        long start = System.currentTimeMillis();
        long sum = 0;
        for (long i = 1; i <= 10_0000_0000; i++) {
            sum += i;
        }
        long end = System.currentTimeMillis();
        System.out.println("sum=" + sum + ", 所用时间为:" + (end - start));
    }

    /**
     * ForkJoin计算任务计算
     */
    public static void test2() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        SumTask sumTask = new SumTask(0L, 10_0000_0000L);
        ForkJoinTask<Long> forkJoinTask = forkJoinPool.submit(sumTask);
        Long sum = forkJoinTask.get();

        long end = System.currentTimeMillis();
        System.out.println("sum=" + sum + ", 所用时间为:" + (end - start));
    }

    /**
     * Stream流计算
     */
    public static void test3() {
        long start = System.currentTimeMillis();
        long sum = LongStream.rangeClosed(0L, 10_0000_0000).parallel().reduce(0, Long::sum);
        long end = System.currentTimeMillis();
        System.out.println("sum=" + sum + ", 所用时间为:" + (end - start));
    }
}
